package look4ss.aplicativo;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.sdsmdg.tastytoast.TastyToast;

import java.util.HashMap;
import java.util.Map;

public class ActivityLogin extends AppCompatActivity {
    private Button botaoLogin;
    private TextView botaoRegistrar, esqueceuSenha;
    private EditText enderecoEmail;
    private EditText usuarioSenha;
    private TextInputLayout txtEmail;
    private TextInputLayout txtSenha;
    private ProgressBar barraDeLoading;
    private CheckBox lembrar;
    private SharedPreferences loginLembrar;
    private SharedPreferences.Editor loginLembrar_edt;
    private SharedPreferences sharp;
    private SharedPreferences.Editor sharp_edt;
    private boolean salvarLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        sharp = getSharedPreferences("loginPrefs", MODE_PRIVATE);

        botaoLogin = findViewById(R.id.login);
        botaoRegistrar = findViewById(R.id.criarconta_botao);
        esqueceuSenha = findViewById(R.id.esqueceusenha);
        enderecoEmail = findViewById(R.id.endereco_de_email);
        usuarioSenha = findViewById(R.id.senha_login);
        txtEmail = findViewById(R.id.layout_entrada_texto);
        txtSenha = findViewById(R.id.layout_entrada_texto2);
        barraDeLoading = findViewById(R.id.barraLoading);
        lembrar = findViewById(R.id.lembrar_login);
        loginLembrar = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        loginLembrar_edt = loginLembrar.edit();

        txtEmail.setHintEnabled(true);
        txtSenha.setHintEnabled(true);

        botaoLogin.setTextColor(ContextCompat.getColor(ActivityLogin.this, R.color.textoBotoes));

        botaoRegistrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ActivityLogin.this, ActivityRegistro.class));
            }
        });

        salvarLogin = loginLembrar.getBoolean("salvarLogin", true);
        if (salvarLogin == true) {
            enderecoEmail.setText(loginLembrar.getString("email", ""));
            usuarioSenha.setText(loginLembrar.getString("senha", ""));
            lembrar.setChecked(true);
        }
        botaoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                InputMethodManager inmng = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inmng.hideSoftInputFromWindow(enderecoEmail.getWindowToken(), 0);

                final String email = enderecoEmail.getText().toString();
                final String senha = usuarioSenha.getText().toString();

                if (lembrar.isChecked()) {
                    loginLembrar_edt.putBoolean("salvarLogin", true);
                    loginLembrar_edt.putString("email", email);
                    loginLembrar_edt.putString("senha", senha);
                    loginLembrar_edt.commit();
                }

                if (TextUtils.isEmpty(email)) {
                    txtEmail.setError(getString(R.string.erro_email_vazio));
                    return;
                } else {
                    txtEmail.setError(null);
                }
                if (TextUtils.isEmpty(senha)) {
                    txtSenha.setError(getString(R.string.erro_senha_vazia));
                } else {
                    txtSenha.setError(null);
                }

                logarUsuario();
                barraDeLoading.setVisibility(View.VISIBLE);
            }
        });
    }

    private void logarUsuario() {
        StringRequest requisicao = new StringRequest(StringRequest.Method.POST, variaveisGlobais.urlApiLogin, new Response.Listener<String>() {
            Map<String, String> params = new HashMap<>();
            @Override
            public void onResponse(String resposta) {
                if(resposta.contains("1")) {
                    loginLembrar_edt.putString("email", enderecoEmail.getText().toString());
                    loginLembrar_edt.putString("senha", usuarioSenha.getText().toString());
                    loginLembrar_edt.commit();
                    sharp_edt = sharp.edit();
                    sharp_edt.putString("estado", "logado");
                    sharp_edt.commit();
                    barraDeLoading.setVisibility(View.GONE);

                    startActivity(new Intent(ActivityLogin.this, posLogin.class));
                }else{
                    TastyToast.makeText(getApplicationContext(), "Credenciais de login incorretas!", Toast.LENGTH_SHORT, TastyToast.ERROR);
                    barraDeLoading.setVisibility(View.GONE);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                   // loginLembrar = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("login", "true");
                params.put("email", enderecoEmail.getText().toString().trim());
                params.put("senha", usuarioSenha.getText().toString().trim());
                return params;
            }
        };
        Volley.newRequestQueue(this).add(requisicao);
    }
}